package control;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.dao.Course_MajorDao;
import model.dao.CoursesDao;
import model.dao.MajorDao;

/**
 * Servlet implementation class GetCourse
 */
@WebServlet("/GetCourse")
public class GetCourse extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetCourse() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		List<Object> cMList = null,courseName=new ArrayList<>();
		String str=null;
		courseName.clear();
		String majorValue=(String)request.getParameter("text1");
		HttpSession session=request.getSession(true);
		session.setAttribute("major", majorValue);
		System.out.println(majorValue);
		MajorDao majordao=new MajorDao();
		Course_MajorDao cM=new Course_MajorDao();
		CoursesDao coursedao=new CoursesDao();
		Object id=new String("id");
		Object name=new String("name");
		Object md=new String(majorValue);
		Object courseid=new String("course_id");
		Object majorid=new String("major_id");
		List<Object> majorList=majordao.getSigleSelect(id, name, md);
		for (Object object : majorList) {
			cMList=cM.getSigleSelect(courseid, majorid, object);
		}
		
		for (Object object1 : cMList) {
			List<Object> cname=coursedao.getSigleSelect(name, id, object1);
			for (Object object2 : cname) {
				System.out.println(object2);
				courseName.add(object2);
			}
		}
		
		str="[";
		for (Object courName : courseName) {
			str+="{\"name\":\"" + (String)courName + "\"},";
		}
		str=str.substring(0, str.length()-1);
		str+="]";
		response.setCharacterEncoding("utf-8");
		PrintWriter out=response.getWriter();
		out.print(str);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
